<template>
	<view class="content">
		<u--input shape="circle" placeholder="搜索..." prefixIcon="search"
			prefixIconStyle="font-size: 29px;color: #909399" v-model="page.title"
			:customStyle="{backgroundColor:'#f6f6f6',padding:'15rpx 30rpx',boxSizing:' border-box'}"
			@change="search()"></u--input>
		<u-empty v-if="chatlist.length <= 0" mode="list" width="50%" textSize="30"
			icon="http://cdn.uviewui.com/uview/empty/list.png">
		</u-empty>
		<view v-else class="message" v-for="(item,index) in chatlist" :key="index">
			<u-badge :offset="[-10,560]" :absolute="true" :type="type" max="99" :value="unQuantity[item.id]"></u-badge>
			<view class="message-box" @click="gomessage(item)">
				<view class="message-image" v-if="item.avatar">
					<image
						:src="item.avatar ? $u.fileBaseUrl+item.avatar.split(',')[0] :'../../static/images/me/default-avatar-orange.png' "
						mode="aspectFill"></image>
					<image
						:src="item.avatar ? $u.fileBaseUrl+item.avatar.split(',')[1] :'../../static/images/me/default-avatar-orange.png' "
						mode="aspectFill"></image>
					<image
						:src="item.avatar ? $u.fileBaseUrl+ item.avatar.split(',')[2] :'../../static/images/me/default-avatar-orange.png' "
						mode="aspectFill">
					</image>
				</view>
				<image v-else class="image" src="../../static/images/me/default-avatar-orange.png" mode="aspectFit">
				</image>
				<view class="message-center">
					<view class="message-title">
						{{item.title.replace(/^\[\d+]/, '')}}
					</view>
					<view class="message-text">
						<view v-if="item.endType==1">
							{{item.isMyMessage==0 ? '' : item.endNickname +':'}}
							<rich-text :nodes="item.endMessage"></rich-text>
						</view>
						<view v-if="item.endType==2">
							{{item.isMyMessage==0 ? '' : item.endNickname+':'}}
							[图片]
						</view>
						<view v-if="item.endType==3">
							{{item.isMyMessage==0 ? '' : item.endNickname+':'}}
							[名片]
						</view>
					</view>
				</view>
			</view>
			<!-- <text>{{item.endMessageTime.substring(11, 16)}}</text> -->
			<text>{{item.endMessageTime? formatMessageTime(item.endMessageTime) :item.createTime.substring(11, 16) }}</text>
		</view>
		<cc-myTabbar :tabBarShow="3"></cc-myTabbar>
	</view>
</template>

<script>
	export default {
		computed: {
			unQuantity() {
				return this.$store.state.unQuantity
			}
		},
		data() {
			return {
				type: "error",
				value: 100,
				chatlist: [],
				total: 0,
				page: {
					pageNum: 1,
					pageSize: 10,
					title: ''
				}
			}
		},
		onLoad() {
			// this.initSendMsg()
			// this.formattedTime = this.formatMessageTime(this.messageTime);
		},
		onShow() {
			this.getchatlist()
			this.initSendMsg()
		},
		// 下拉刷新
		onPullDownRefresh() {
			// 刷新数据的逻辑
			this.page.pageNum = 1
			this.page.pageSize = 10
			this.getchatlist()
			// 模拟异步操作
			setTimeout(() => {
				// 刷新完成后，结束下拉刷新
				uni.stopPullDownRefresh();
				console.log('下拉刷新结束');
			}, 1000);
		},
		// 上拉加载
		onReachBottom() {
			this.loadMore();
		},
		methods: {
			// 查询我的聊天列表
			async getchatlist() {
				let res = await this.$u.api.getchatlist(this.page)
				if (res.code == 200) {
					if (this.page.pageNum == 1) {
						this.chatlist = res.rows;
					} else {
						// 如果不是第一页，追加数据
						this.chatlist = [...this.chatlist, ...res.rows];
					}
					this.total = res.total;
				}
			},
			// 跳转到聊天页面
			gomessage(item) {
				uni.navigateTo({
					url: `/packagesMessage/message/message?chatId=${item.id}&name=${item.title}`
				})
			},
			// 搜索群聊
			search() {
				this.getchatlist()
			},
			// 上拉加载
			loadMore() {
				if (this.chatlist.length >= this.total) {
					uni.showToast({
						title: '没有更多消息了',
						icon: "none"
					});
					return;
				}

				this.page.pageNum += 1;
				uni.showLoading({
					title: '加载中...'
				});

				this.getchatlist().then(() => {
					uni.hideLoading();
				}).catch(error => {
					console.error('加载更多数据时出错:', error);
					uni.hideLoading();
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
				});
			},
			initSendMsg() {
				this.$socket.connectSocketInit(() => {
					//获取消息的函数
					this.$socket.getMessage(this.screenMsg);
				})
			},
			screenMsg(msg) {
				// console.log('消息列表', msg);
				// 查找目标对象的索引
				const index = this.chatlist.findIndex(item => item.id === msg.chatId);
				// 如果找到目标对象
				if (index !== -1) {
					// 从原数组中删除目标对象
					const [item] = this.chatlist.splice(index, 1);
					item.endMessage = msg.content
					item.endMessageTime = msg.sendTime
					item.endType = msg.type
					// 将目标对象插入到数组的开头
					this.chatlist.unshift(item);
				}
			},
			formatMessageTime(messageTime) {
				const currentTime = new Date();
				const currentDateString = currentTime.toDateString();

				const messageDate = new Date(messageTime);
				const messageDateString = messageDate.toDateString();

				if (currentDateString === messageDateString) {
					// 今天的消息
					const hours = messageDate.getHours().toString().padStart(2, '0');
					const minutes = messageDate.getMinutes().toString().padStart(2, '0');
					return `${hours}:${minutes}`;
				} else if (currentTime - messageDate < 24 * 60 * 60 * 1000) {
					// 昨天的消息
					return "昨天";
				} else {
					// 其他日期的消息
					const year = messageDate.getFullYear();
					const month = (messageDate.getMonth() + 1).toString().padStart(2, '0');
					const day = messageDate.getDate().toString().padStart(2, '0');
					return `${year}/${month}/${day}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		background-color: #fff;
		padding: 30rpx;
		min-height: 90vh;
		padding-bottom: 100rpx;
		box-sizing: border-box;
		font-size: 24rpx;

		.message {
			margin: 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: relative;

			.message-box {
				display: flex;
				align-items: center;

				.message-image {
					background-color: #e1e1e1;
					width: 120rpx;
					height: 120rpx;
					display: flex;
					flex-wrap: wrap;
					justify-content: space-around;
					margin-right: 20rpx;
					border-radius: 5rpx;

					image {
						width: 48%;
						height: 48%;
						margin: 1%;
					}

				}

				.image {
					width: 120rpx;
					height: 120rpx;
					margin-right: 20rpx;
					border-radius: 2rpx;
				}

				.message-center {
					width: 420rpx;

					.message-title {
						width: 420rpx;
						font-weight: 700;
						font-size: 30rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.message-text {
						font-size: 26rpx;

						view {
							width: 420rpx;
							height: 40rpx;
							display: flex;
							color: #999999;
							margin: 15rpx 0;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}
				}
			}

			text {
				display: block;
				float: right;
				font-size: 24rpx;
				color: #B3B3B3;
			}
		}
	}
</style>